package com.sztz.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 *  ThreadLocal使用场景
 * @author yzy
 * @date 2022/9/13 20:12
 */
@RestController
@RequestMapping("/threadlocal")
public class ThreadLocalLearnController {
    private static final ThreadLocal<Integer> currentUser = ThreadLocal.withInitial(()->null);

    @GetMapping("/wrong")
    public JSONObject threadWrong(@RequestParam("userId") Integer userId){
        String before = StrUtil.format("线程{} 获取当前用户ID:{}",Thread.currentThread().getName(),currentUser.get());
        currentUser.set(userId);
        String after = StrUtil.format("线程{} 获取当前用户ID:{}",Thread.currentThread().getName(),currentUser.get());
        JSONObject object = new JSONObject();
        object.put("before",before);
        object.put("after",after);
        return object;
    }

    @GetMapping("/right")
    public JSONObject threadRight(@RequestParam("userId") Integer userId){
        String before = StrUtil.format("线程{} 获取当前用户ID:{}",Thread.currentThread().getName(),currentUser.get());
        currentUser.set(userId);
        try {
            String after = StrUtil.format("线程{} 获取当前用户ID:{}", Thread.currentThread().getName(), currentUser.get());
            JSONObject object = new JSONObject();
            object.put("before", before);
            object.put("after", after);
            return object;
        }finally {
            currentUser.remove();
        }
    }
}
